package app.engine.solucoes.request.servico;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import app.engine.solucoes.request.beans.Pergunta;
import app.engine.solucoes.request.beans.Usuario;
import app.engine.solucoes.request.dao.AppDAO;

@SuppressWarnings("serial")
public class SendMail extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		AppDAO dao = new AppDAO();
		List<Object> usuarios = dao.selectAll(Usuario.class);
		List<Object> perguntas = dao.selectAll(Pergunta.class);
		StringBuilder sb = new StringBuilder();
		EmailService emailService = new EmailService();
		List<Usuario> destinatarios = new ArrayList<Usuario>();
		SimpleDateFormat sd = new SimpleDateFormat("dd/MM/yyyy");
		
		Integer cont = new Integer(1);
		for (Object usuario : usuarios) {
			Usuario user = (Usuario) usuario;
			destinatarios.clear();
			cont = new Integer(1);
			for (Object pergunta : perguntas) {
				Pergunta perg = (Pergunta) pergunta;
				if (user.getEhModerador() && user.getEmpresa().equals(perg.getEmpresa()) && !perg.getAprovada()) {
					sb.append(sd.format(perg.getDataCriacao())).append(" [").append("Pergunta - ").append(cont).append("] ").append(perg.getTxtPergunta()).append("\n\n");
					destinatarios.add(user);
					cont++;
				}
			}
			if (!destinatarios.isEmpty()) {
				emailService.sendMail(destinatarios, "Perguntas nao aprovadas:\n\n\n" + sb.toString(), "FAQs pendentes de aprovacao");
				sb = new StringBuilder();
			}
		}
		
	}
}